package edu.lingnan.lingnanblog.controller;

import edu.lingnan.lingnanblog.entity.Blogger;
import edu.lingnan.lingnanblog.service.BloggerClientService;
import edu.lingnan.lingnanblog.utils.DateUtil;
import edu.lingnan.lingnanblog.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wuyuan
 * @since 2020-06-13 22:25
 */
@Controller
@RequestMapping("/consumer/blogger")
public class BloggerConsumerController {

    @Autowired
    BloggerClientService bloggerClientService;

    @RequestMapping("selectOne/{id}")
    @ResponseBody
    public Blogger selectOne(@PathVariable("id") Integer id){
        return this.bloggerClientService.selectOne(id);
    }

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("toReg")
    public String toReg(){
        return "register";
    }

    @RequestMapping("toEdit")
    public String toEdit(Model model){
        return "admin/modifyInfo";
    }

    @PostMapping("login")
    public String login(String name, String password, Model model, HttpSession session){
        System.out.println("login:::name:::" + name + ", password:::" + password);
        Blogger blogger = bloggerClientService.login(name, password);
        if (blogger == null){
            model.addAttribute("msg", "用户名或者密码错误！");

            return "login";
        }else {
            model.addAttribute("loginUser", blogger.getName());
            session.setAttribute("loginBlogger", blogger);
            return "admin/main";
        }
    }
    @PostMapping("reg")
    public String reg(@Valid Blogger bean, BindingResult br, String cfmpassword, Model model) {
        System.out.println("reg:::" + bean);
        System.out.println("reg:::" + cfmpassword);
        //判断两次密码是否一致
        if(!bean.getPassword().equals(cfmpassword)) {
            model.addAttribute("msg", "两次输入密码不一致");
            return "register";
        }
        //数据较验
        if(br.hasErrors()) {
            Map<String, String> errors = new HashMap<String, String>();
            System.out.println("==============================表单数据出错=================================");
            List<FieldError> fieldErrors = br.getFieldErrors();
            for (FieldError item : fieldErrors) {
                System.out.println(item.getField());
                System.out.println(item.getDefaultMessage());
                errors.put(item.getField(), item.getDefaultMessage());
            }
            model.addAttribute("errors", errors);
            return "register";
        }

        //判断用户名重复
        if (bloggerClientService.getByName(bean.getName()) != null) {
            model.addAttribute("msg", "该用户名已经被使用");
            return "register";
        }

        boolean result = bloggerClientService.reg(bean);
        if (result) {
            System.out.println("注册成功");
            return "login";
        }
        System.out.println("注册失败");
        model.addAttribute("msg", "注册失败");

        return "register";
    }

    @RequestMapping("/save")
    public String save(@RequestParam("imageFile") MultipartFile imageFile, Blogger blogger, Model model,
                       BindingResult br, HttpServletRequest request, HttpServletResponse response)throws Exception{
        if(!imageFile.isEmpty()){
            String filePath=request.getServletContext().getRealPath("/");
            String imageName= DateUtil.getCurrentDateStr()+"."+imageFile.getOriginalFilename().split("\\.")[1];
            imageFile.transferTo(new File("D:\\IntelliJ IDEA 2019.3.1\\workspace4\\springcloud-blog\\lingnanblog-consumer-blogger-feign\\src\\main\\resources\\static\\userImages/"+imageName));
            blogger.setImageName(imageName);
        }
        System.out.println(blogger);
        boolean resultTotal=bloggerClientService.save(blogger);
        System.out.println(resultTotal);
        StringBuffer result=new StringBuffer();
        if(resultTotal){
            result.append("<script language='javascript'>alert('修改成功');window.location.href='../modifyInfo.jsp'</script>");
        }else{
            result.append("<script language='javascript'>alert('修改失败');</script>");
        }
        ResponseUtil.write(response, result);
        return null;
    }
//    http://localhost:9527/lingnanblog-provider-blogger/consumer/blogger/toLogin
}
